<template>
  <ContentWrap>
    <!-- 搜索工作栏 -->
    <el-form
      class="-mb-15px"
      :model="queryParams"
      ref="queryFormRef"
      :inline="true"
      label-width="68px"
    >
      <el-form-item label="客户编号" prop="customerNo">
        <el-input
          v-model="queryParams.customerNo"
          placeholder="请输入客户编号"
          clearable
          @keyup.enter="handleQuery"
          class="!w-240px"
        />
      </el-form-item>
      <el-form-item label="平台客户ID" prop="platformCustomerId">
        <el-input
          v-model="queryParams.platformCustomerId"
          placeholder="请输入平台客户ID"
          clearable
          @keyup.enter="handleQuery"
          class="!w-240px"
        />
      </el-form-item>
      <el-form-item label="邮箱" prop="email">
        <el-input
          v-model="queryParams.email"
          placeholder="请输入邮箱"
          clearable
          @keyup.enter="handleQuery"
          class="!w-240px"
        />
      </el-form-item>
      <el-form-item label="手机号" prop="phone">
        <el-input
          v-model="queryParams.phone"
          placeholder="请输入手机号"
          clearable
          @keyup.enter="handleQuery"
          class="!w-240px"
        />
      </el-form-item>
      <el-form-item label="名" prop="firstName">
        <el-input
          v-model="queryParams.firstName"
          placeholder="请输入名"
          clearable
          @keyup.enter="handleQuery"
          class="!w-240px"
        />
      </el-form-item>
      <el-form-item label="姓" prop="lastName">
        <el-input
          v-model="queryParams.lastName"
          placeholder="请输入姓"
          clearable
          @keyup.enter="handleQuery"
          class="!w-240px"
        />
      </el-form-item>
      <el-form-item label="全名" prop="fullName">
        <el-input
          v-model="queryParams.fullName"
          placeholder="请输入全名"
          clearable
          @keyup.enter="handleQuery"
          class="!w-240px"
        />
      </el-form-item>
      <el-form-item label="昵称" prop="nickname">
        <el-input
          v-model="queryParams.nickname"
          placeholder="请输入昵称"
          clearable
          @keyup.enter="handleQuery"
          class="!w-240px"
        />
      </el-form-item>
      <el-form-item label="头像" prop="avatar">
        <el-input
          v-model="queryParams.avatar"
          placeholder="请输入头像"
          clearable
          @keyup.enter="handleQuery"
          class="!w-240px"
        />
      </el-form-item>
      <el-form-item label="性别" prop="gender">
        <el-select
          v-model="queryParams.gender"
          placeholder="请选择性别"
          clearable
          class="!w-240px"
        >
          <el-option
            v-for="dict in getIntDictOptions(DICT_TYPE.CROSSBORDER_CUSTOMER_GENDER)"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="生日" prop="birthday">
        <el-input
          v-model="queryParams.birthday"
          placeholder="请输入生日"
          clearable
          @keyup.enter="handleQuery"
          class="!w-240px"
        />
      </el-form-item>
      <el-form-item label="年龄" prop="age">
        <el-input
          v-model="queryParams.age"
          placeholder="请输入年龄"
          clearable
          @keyup.enter="handleQuery"
          class="!w-240px"
        />
      </el-form-item>
      <el-form-item label="语言代码" prop="languageCode">
        <el-input
          v-model="queryParams.languageCode"
          placeholder="请输入语言代码"
          clearable
          @keyup.enter="handleQuery"
          class="!w-240px"
        />
      </el-form-item>
      <el-form-item label="货币代码" prop="currencyCode">
        <el-input
          v-model="queryParams.currencyCode"
          placeholder="请输入货币代码"
          clearable
          @keyup.enter="handleQuery"
          class="!w-240px"
        />
      </el-form-item>
      <el-form-item label="时区" prop="timezone">
        <el-input
          v-model="queryParams.timezone"
          placeholder="请输入时区"
          clearable
          @keyup.enter="handleQuery"
          class="!w-240px"
        />
      </el-form-item>
      <el-form-item label="客户类型" prop="customerType">
        <el-select
          v-model="queryParams.customerType"
          placeholder="请选择客户类型"
          clearable
          class="!w-240px"
        >
          <el-option
            v-for="dict in getIntDictOptions(DICT_TYPE.CROSSBORDER_CUSTOMER_TYPE)"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="客户等级" prop="customerLevel">
        <el-select
          v-model="queryParams.customerLevel"
          placeholder="请选择客户等级"
          clearable
          class="!w-240px"
        >
          <el-option
            v-for="dict in getIntDictOptions(DICT_TYPE.CROSSBORDER_CUSTOMER_LEVEL)"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="公司名称" prop="companyName">
        <el-input
          v-model="queryParams.companyName"
          placeholder="请输入公司名称"
          clearable
          @keyup.enter="handleQuery"
          class="!w-240px"
        />
      </el-form-item>
      <el-form-item label="税号" prop="taxNumber">
        <el-input
          v-model="queryParams.taxNumber"
          placeholder="请输入税号"
          clearable
          @keyup.enter="handleQuery"
          class="!w-240px"
        />
      </el-form-item>
      <el-form-item label="营业执照号" prop="businessLicense">
        <el-input
          v-model="queryParams.businessLicense"
          placeholder="请输入营业执照号"
          clearable
          @keyup.enter="handleQuery"
          class="!w-240px"
        />
      </el-form-item>
      <el-form-item label="注册来源" prop="registrationSource">
        <el-input
          v-model="queryParams.registrationSource"
          placeholder="请输入注册来源"
          clearable
          @keyup.enter="handleQuery"
          class="!w-240px"
        />
      </el-form-item>
      <el-form-item label="注册IP" prop="registrationIp">
        <el-input
          v-model="queryParams.registrationIp"
          placeholder="请输入注册IP"
          clearable
          @keyup.enter="handleQuery"
          class="!w-240px"
        />
      </el-form-item>
      <el-form-item label="注册时间" prop="registrationTime">
        <el-date-picker
          v-model="queryParams.registrationTime"
          value-format="YYYY-MM-DD HH:mm:ss"
          type="daterange"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
          :default-time="[new Date('1 00:00:00'), new Date('1 23:59:59')]"
          class="!w-220px"
        />
      </el-form-item>
      <el-form-item label="最后登录时间" prop="lastLoginTime">
        <el-date-picker
          v-model="queryParams.lastLoginTime"
          value-format="YYYY-MM-DD HH:mm:ss"
          type="daterange"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
          :default-time="[new Date('1 00:00:00'), new Date('1 23:59:59')]"
          class="!w-220px"
        />
      </el-form-item>
      <el-form-item label="最后登录IP" prop="lastLoginIp">
        <el-input
          v-model="queryParams.lastLoginIp"
          placeholder="请输入最后登录IP"
          clearable
          @keyup.enter="handleQuery"
          class="!w-240px"
        />
      </el-form-item>
      <el-form-item label="总订单数" prop="totalOrderCount">
        <el-input
          v-model="queryParams.totalOrderCount"
          placeholder="请输入总订单数"
          clearable
          @keyup.enter="handleQuery"
          class="!w-240px"
        />
      </el-form-item>
      <el-form-item label="总订单金额" prop="totalOrderAmount">
        <el-input
          v-model="queryParams.totalOrderAmount"
          placeholder="请输入总订单金额"
          clearable
          @keyup.enter="handleQuery"
          class="!w-240px"
        />
      </el-form-item>
      <el-form-item label="总支付金额" prop="totalPaidAmount">
        <el-input
          v-model="queryParams.totalPaidAmount"
          placeholder="请输入总支付金额"
          clearable
          @keyup.enter="handleQuery"
          class="!w-240px"
        />
      </el-form-item>
      <el-form-item label="平均订单金额" prop="avgOrderAmount">
        <el-input
          v-model="queryParams.avgOrderAmount"
          placeholder="请输入平均订单金额"
          clearable
          @keyup.enter="handleQuery"
          class="!w-240px"
        />
      </el-form-item>
      <el-form-item label="最后下单时间" prop="lastOrderTime">
        <el-date-picker
          v-model="queryParams.lastOrderTime"
          value-format="YYYY-MM-DD HH:mm:ss"
          type="daterange"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
          :default-time="[new Date('1 00:00:00'), new Date('1 23:59:59')]"
          class="!w-220px"
        />
      </el-form-item>
      <el-form-item label="信用额度" prop="creditLimit">
        <el-input
          v-model="queryParams.creditLimit"
          placeholder="请输入信用额度"
          clearable
          @keyup.enter="handleQuery"
          class="!w-240px"
        />
      </el-form-item>
      <el-form-item label="已用信用额度" prop="creditUsed">
        <el-input
          v-model="queryParams.creditUsed"
          placeholder="请输入已用信用额度"
          clearable
          @keyup.enter="handleQuery"
          class="!w-240px"
        />
      </el-form-item>
      <el-form-item label="积分余额" prop="pointsBalance">
        <el-input
          v-model="queryParams.pointsBalance"
          placeholder="请输入积分余额"
          clearable
          @keyup.enter="handleQuery"
          class="!w-240px"
        />
      </el-form-item>
      <el-form-item label="累计积分" prop="pointsTotal">
        <el-input
          v-model="queryParams.pointsTotal"
          placeholder="请输入累计积分"
          clearable
          @keyup.enter="handleQuery"
          class="!w-240px"
        />
      </el-form-item>
      <el-form-item label="客户状态" prop="status">
        <el-select
          v-model="queryParams.status"
          placeholder="请选择客户状态"
          clearable
          class="!w-240px"
        >
          <el-option
            v-for="dict in getIntDictOptions(DICT_TYPE.CROSSBORDER_CUSTOMER_STATUS)"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="邮箱是否验证" prop="emailVerified">
        <el-select
          v-model="queryParams.emailVerified"
          placeholder="请选择邮箱是否验证"
          clearable
          class="!w-240px"
        >
          <el-option label="请选择字典生成" value="" />
        </el-select>
      </el-form-item>
      <el-form-item label="手机是否验证" prop="phoneVerified">
        <el-select
          v-model="queryParams.phoneVerified"
          placeholder="请选择手机是否验证"
          clearable
          class="!w-240px"
        >
          <el-option label="请选择字典生成" value="" />
        </el-select>
      </el-form-item>
      <el-form-item label="KYC状态" prop="kycStatus">
        <el-select
          v-model="queryParams.kycStatus"
          placeholder="请选择KYC状态"
          clearable
          class="!w-240px"
        >
          <el-option
            v-for="dict in getIntDictOptions(DICT_TYPE.CROSSBORDER_KYC_STATUS)"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="风险等级" prop="riskLevel">
        <el-select
          v-model="queryParams.riskLevel"
          placeholder="请选择风险等级"
          clearable
          class="!w-240px"
        >
          <el-option
            v-for="dict in getIntDictOptions(DICT_TYPE.CROSSBORDER_RISK_LEVEL)"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="客户标签，逗号分隔" prop="tags">
        <el-input
          v-model="queryParams.tags"
          placeholder="请输入客户标签，逗号分隔"
          clearable
          @keyup.enter="handleQuery"
          class="!w-240px"
        />
      </el-form-item>
      <el-form-item label="备注" prop="remark">
        <el-input
          v-model="queryParams.remark"
          placeholder="请输入备注"
          clearable
          @keyup.enter="handleQuery"
          class="!w-240px"
        />
      </el-form-item>
      <el-form-item label="创建时间" prop="createTime">
        <el-date-picker
          v-model="queryParams.createTime"
          value-format="YYYY-MM-DD HH:mm:ss"
          type="daterange"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
          :default-time="[new Date('1 00:00:00'), new Date('1 23:59:59')]"
          class="!w-220px"
        />
      </el-form-item>
      <el-form-item>
        <el-button @click="handleQuery"><Icon icon="ep:search" class="mr-5px" /> 搜索</el-button>
        <el-button @click="resetQuery"><Icon icon="ep:refresh" class="mr-5px" /> 重置</el-button>
        <el-button
          type="primary"
          plain
          @click="openForm('create')"
          v-hasPermi="['crossborder:order-customer:create']"
        >
          <Icon icon="ep:plus" class="mr-5px" /> 新增
        </el-button>
        <el-button
          type="success"
          plain
          @click="handleExport"
          :loading="exportLoading"
          v-hasPermi="['crossborder:order-customer:export']"
        >
          <Icon icon="ep:download" class="mr-5px" /> 导出
        </el-button>
        <el-button
            type="danger"
            plain
            :disabled="isEmpty(checkedIds)"
            @click="handleDeleteBatch"
            v-hasPermi="['crossborder:order-customer:delete']"
        >
          <Icon icon="ep:delete" class="mr-5px" /> 批量删除
        </el-button>
      </el-form-item>
    </el-form>
  </ContentWrap>

  <!-- 列表 -->
  <ContentWrap>
    <el-table
        row-key="id"
        v-loading="loading"
        :data="list"
        :stripe="true"
        :show-overflow-tooltip="true"
        @selection-change="handleRowCheckboxChange"
    >
    <el-table-column type="selection" width="55" />
      <el-table-column label="客户编号" align="center" prop="id" />
      <el-table-column label="客户编号" align="center" prop="customerNo" />
      <el-table-column label="平台客户ID" align="center" prop="platformCustomerId" />
      <el-table-column label="邮箱" align="center" prop="email" />
      <el-table-column label="手机号" align="center" prop="phone" />
      <el-table-column label="名" align="center" prop="firstName" />
      <el-table-column label="姓" align="center" prop="lastName" />
      <el-table-column label="全名" align="center" prop="fullName" />
      <el-table-column label="昵称" align="center" prop="nickname" />
      <el-table-column label="头像" align="center" prop="avatar" />
      <el-table-column label="性别" align="center" prop="gender" />
      <el-table-column label="生日" align="center" prop="birthday" />
      <el-table-column label="年龄" align="center" prop="age" />
      <el-table-column label="语言代码" align="center" prop="languageCode" />
      <el-table-column label="货币代码" align="center" prop="currencyCode" />
      <el-table-column label="时区" align="center" prop="timezone" />
      <el-table-column label="客户类型" align="center" prop="customerType" />
      <el-table-column label="客户等级" align="center" prop="customerLevel" />
      <el-table-column label="公司名称" align="center" prop="companyName" />
      <el-table-column label="税号" align="center" prop="taxNumber" />
      <el-table-column label="营业执照号" align="center" prop="businessLicense" />
      <el-table-column label="注册来源" align="center" prop="registrationSource" />
      <el-table-column label="注册IP" align="center" prop="registrationIp" />
      <el-table-column
        label="注册时间"
        align="center"
        prop="registrationTime"
        :formatter="dateFormatter"
        width="180px"
      />
      <el-table-column
        label="最后登录时间"
        align="center"
        prop="lastLoginTime"
        :formatter="dateFormatter"
        width="180px"
      />
      <el-table-column label="最后登录IP" align="center" prop="lastLoginIp" />
      <el-table-column label="总订单数" align="center" prop="totalOrderCount" />
      <el-table-column label="总订单金额" align="center" prop="totalOrderAmount" />
      <el-table-column label="总支付金额" align="center" prop="totalPaidAmount" />
      <el-table-column label="平均订单金额" align="center" prop="avgOrderAmount" />
      <el-table-column
        label="最后下单时间"
        align="center"
        prop="lastOrderTime"
        :formatter="dateFormatter"
        width="180px"
      />
      <el-table-column label="信用额度" align="center" prop="creditLimit" />
      <el-table-column label="已用信用额度" align="center" prop="creditUsed" />
      <el-table-column label="积分余额" align="center" prop="pointsBalance" />
      <el-table-column label="累计积分" align="center" prop="pointsTotal" />
      <el-table-column label="客户状态" align="center" prop="status" />
      <el-table-column label="邮箱是否验证" align="center" prop="emailVerified" />
      <el-table-column label="手机是否验证" align="center" prop="phoneVerified" />
      <el-table-column label="KYC状态" align="center" prop="kycStatus" />
      <el-table-column label="风险等级" align="center" prop="riskLevel" />
      <el-table-column label="客户标签，逗号分隔" align="center" prop="tags" />
      <el-table-column label="备注" align="center" prop="remark" />
      <el-table-column
        label="创建时间"
        align="center"
        prop="createTime"
        :formatter="dateFormatter"
        width="180px"
      />
      <el-table-column label="操作" align="center" min-width="120px">
        <template #default="scope">
          <el-button
            link
            type="primary"
            @click="openForm('update', scope.row.id)"
            v-hasPermi="['crossborder:order-customer:update']"
          >
            编辑
          </el-button>
          <el-button
            link
            type="danger"
            @click="handleDelete(scope.row.id)"
            v-hasPermi="['crossborder:order-customer:delete']"
          >
            删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>
    <!-- 分页 -->
    <Pagination
      :total="total"
      v-model:page="queryParams.pageNo"
      v-model:limit="queryParams.pageSize"
      @pagination="getList"
    />
  </ContentWrap>

  <!-- 表单弹窗：添加/修改 -->
  <OrderCustomerForm ref="formRef" @success="getList" />
</template>

<script setup lang="ts">
import { isEmpty } from '@/utils/is'
import { dateFormatter } from '@/utils/formatTime'
import download from '@/utils/download'
import { OrderCustomerApi, OrderCustomer } from '@/api/crossborder/ordercustomer'
import OrderCustomerForm from './OrderCustomerForm.vue'
import { DICT_TYPE, getIntDictOptions } from '@/utils/dict'

/** 跨境电商客户信息 列表 */
defineOptions({ name: 'OrderCustomer' })

const message = useMessage() // 消息弹窗
const { t } = useI18n() // 国际化

const loading = ref(true) // 列表的加载中
const list = ref<OrderCustomer[]>([]) // 列表的数据
const total = ref(0) // 列表的总页数
const queryParams = reactive({
  pageNo: 1,
  pageSize: 10,
  customerNo: undefined,
  platformCustomerId: undefined,
  email: undefined,
  phone: undefined,
  firstName: undefined,
  lastName: undefined,
  fullName: undefined,
  nickname: undefined,
  avatar: undefined,
  gender: undefined,
  birthday: undefined,
  age: undefined,
  languageCode: undefined,
  currencyCode: undefined,
  timezone: undefined,
  customerType: undefined,
  customerLevel: undefined,
  companyName: undefined,
  taxNumber: undefined,
  businessLicense: undefined,
  registrationSource: undefined,
  registrationIp: undefined,
  registrationTime: [],
  lastLoginTime: [],
  lastLoginIp: undefined,
  totalOrderCount: undefined,
  totalOrderAmount: undefined,
  totalPaidAmount: undefined,
  avgOrderAmount: undefined,
  lastOrderTime: [],
  creditLimit: undefined,
  creditUsed: undefined,
  pointsBalance: undefined,
  pointsTotal: undefined,
  status: undefined,
  emailVerified: undefined,
  phoneVerified: undefined,
  kycStatus: undefined,
  riskLevel: undefined,
  tags: undefined,
  remark: undefined,
  createTime: [],
})
const queryFormRef = ref() // 搜索的表单
const exportLoading = ref(false) // 导出的加载中

/** 查询列表 */
const getList = async () => {
  loading.value = true
  try {
    const data = await OrderCustomerApi.getOrderCustomerPage(queryParams)
    list.value = data.list
    total.value = data.total
  } finally {
    loading.value = false
  }
}

/** 搜索按钮操作 */
const handleQuery = () => {
  queryParams.pageNo = 1
  getList()
}

/** 重置按钮操作 */
const resetQuery = () => {
  queryFormRef.value.resetFields()
  handleQuery()
}

/** 添加/修改操作 */
const formRef = ref()
const openForm = (type: string, id?: number) => {
  formRef.value.open(type, id)
}

/** 删除按钮操作 */
const handleDelete = async (id: number) => {
  try {
    // 删除的二次确认
    await message.delConfirm()
    // 发起删除
    await OrderCustomerApi.deleteOrderCustomer(id)
    message.success(t('common.delSuccess'))
    currentRow.value = {}
    // 刷新列表
    await getList()
  } catch {}
}

/** 批量删除跨境电商客户信息 */
const handleDeleteBatch = async () => {
  try {
    // 删除的二次确认
    await message.delConfirm()
    await OrderCustomerApi.deleteOrderCustomerList(checkedIds.value);
    message.success(t('common.delSuccess'))
    await getList();
  } catch {}
}

const checkedIds = ref<number[]>([])
const handleRowCheckboxChange = (records: OrderCustomer[]) => {
  checkedIds.value = records.map((item) => item.id);
}

/** 导出按钮操作 */
const handleExport = async () => {
  try {
    // 导出的二次确认
    await message.exportConfirm()
    // 发起导出
    exportLoading.value = true
    const data = await OrderCustomerApi.exportOrderCustomer(queryParams)
    download.excel(data, '跨境电商客户信息.xls')
  } catch {
  } finally {
    exportLoading.value = false
  }
}

/** 初始化 **/
onMounted(() => {
  getList()
})
</script>